package xiaobange.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xiaobange.common.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    //默认路径
    @Value("${upload.path}")
    private String Path;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //获取上传的文件名
        String originalFilename = file.getOriginalFilename();
        //截取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //UUID生成随机文件名,并且把后缀给他拼接在一起
        String FileName = UUID.randomUUID().toString() + substring;
        //判断路径是否存在
        File FileDir = new File(Path);
        if (!FileDir.exists()){
            //创建文件夹
            FileDir.mkdirs();
        }
        try {
            //转存文件到指定位置
            file.transferTo(new File(Path + FileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(FileName);
    }


    @GetMapping("download")
    public void download(String name, HttpServletResponse request){
        //输入流，通过输入流读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(Path + name));
            //输出流，像浏览器输出文件
            ServletOutputStream outputStream = request.getOutputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) > 0){
                //网浏览器写入数据
                outputStream.write(bytes,0,len);
                //刷新
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            //throw new RuntimeException(e);
            log.info("未找到相关图片：{}",e.getMessage());
        } catch (IOException e) {
            //throw new RuntimeException(e);
        }
    }
}
